package codename.primavera.test;


import java.sql.Connection;

import javax.sql.DataSource;

import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

/**
 * @author AIEXM45
 * 
 */
public class DbUnitSpringJUnit4ClassRunner{

	@Autowired
	private DataSource dataSource;

	@Before
	public void init() throws Exception {
		// insert data into db
		DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
	}

	@After
	public void after() throws Exception {
		// insert data into db
		DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
	}

	private IDatabaseConnection getConnection() throws Exception {
		// get connection
		Connection con = dataSource.getConnection();
		// oracle schema name is the user name
		// databaseMetaData.getSchemas().toString()
		// org.hsqldb.util.DatabaseManagerSwing.main(new String[]{});
		IDatabaseConnection connection = new DatabaseConnection(con);
		DatabaseConfig config = connection.getConfig();
		config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
				new HsqldbDataTypeFactory());
		return connection;
	}

	private IDataSet getDataSet() throws Exception {
		return new XlsDataSet(new ClassPathResource(getDataSetLocation()).getInputStream());
	}
	
	protected String getDataSetLocation() {
		return "src/main/resources/dataset.xls";
	}

}
